package com.xsq.newmall01.Controller;

import com.xsq.newmall01.Dao.MerchantUser;
import com.xsq.newmall01.Dao.Order;
import com.xsq.newmall01.Dao.Ownership;
import com.xsq.newmall01.Dao.User;
import com.xsq.newmall01.Dto.OrderCreateDTO;
import com.xsq.newmall01.Service.MerchantUserService.MOrderService;
import com.xsq.newmall01.Service.UserService.UOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/orders")
public class OrderController {

    // 商家订单服务
    @Autowired
    @Qualifier("merchantorderservice")
    private MOrderService merchantMOrderService;

    // 用户订单服务
    @Autowired
    @Qualifier("userorderservice")
    private UOrderService userUOrderService;

    /**
     * 用户创建订单
     */
    @PostMapping("/create")
    public Map<String, Object> createOrder(@RequestBody OrderCreateDTO dto) { // 接收DTO对象
        Map<String, Object> result = new HashMap<>();
        try {
            // 从DTO中获取订单和所有权对象
            userUOrderService.createOrder(dto.getOrder(), dto.getOwnership());
            result.put("success", true);
            result.put("message", "订单创建成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "订单创建失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 用户查询自己的订单
     */
    @PostMapping("/user/owned")
    public Map<String, Object> getUserOwnedOrders(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Order> orders = userUOrderService.getOwnedOrders(user);
            result.put("success", true);
            result.put("data", orders);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 商家查询自己的订单
     */
    @PostMapping("/merchant/owned")
    public Map<String, Object> getMerchantOwnedOrders(@RequestBody MerchantUser merchantUser) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Order> orders = merchantMOrderService.getOwnOrders(merchantUser);
            result.put("success", true);
            result.put("data", orders);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败：" + e.getMessage());
        }
        return result;
    }
}